﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using RxxAdmin.Common;
using RxxAdmin.Common.Helper;
using RxxAdmin.Common.HttpContextUser;
using RxxAdmin.Extensions.Authorizations;
using RxxAdmin.IServices;
using RxxAdmin.Model;
using RxxAdmin.Model.Logs;
using RxxAdmin.Model.ViewModels;

namespace RxxAdmin.Api.Controllers.permission;
/// <summary>
/// 登录服务
/// </summary>
public class SysLoginController : BaseApiController
{
    private readonly ISysUserService _sysUserService;
    private readonly ILoginLogService _loginLogService;
    private readonly IHttpContextAccessor _httpContextAccessor;
    private readonly IUser _user;

    public SysLoginController(ISysUserService sysUserService,
        ILoginLogService loginLogService,
        IHttpContextAccessor httpContextAccessor,
        IUser user)
    {
        _sysUserService = sysUserService;
        _loginLogService = loginLogService;
        _httpContextAccessor = httpContextAccessor;
        _user = user;
    }

    /// <summary>
    /// 用户登录
    /// </summary>
    /// <returns></returns>
    [HttpPost]
    [AllowAnonymous]
    [OperLog("用户登录", OperEnum.Select)]
    public async Task<MessageModel<string>> Login(SysUserLoginIn input)
    {
        string jwtStr = string.Empty;
        if (string.IsNullOrEmpty(input.Account) || string.IsNullOrEmpty(input.PassWord))
            return Failed<string>("用户名或密码不能为空");

        input.PassWord = MD5Helper.MD5Encrypt32(input.PassWord);
        var user = await _sysUserService.Query(d =>
                    d.LoginName == input.Account && d.LoginPWD == input.PassWord);
        if (user.Count > 0)
        {
            var token = JwtHelper.GetToken(user[0].Id.ToString(), user[0].LoginName);
            await _loginLogService.Add(input.Account, "登录成功");
            return Success(token, "获取成功");
        }
        else
        {
            await _loginLogService.Add(input.Account, "登录失败");
            return Failed<string>("认证失败");
        }
    }

    /// <summary>
    /// 获取登录用户的信息
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    [OperLog("获取用户信息", OperEnum.Select)]
    public async Task<MessageModel<SysUserInfoOut>> GetUserInfo()
    {
        var user = await _sysUserService.GetUserInfo(_user.ID);
        var role = await _sysUserService.GetUserRoleNameStr(user.LoginName, user.LoginPWD);
        return Success(new SysUserInfoOut()
        {
            userId = Convert.ToInt32(user.Id),
            userName = user.RealName,
            roles = role
        });
    }

    /// <summary>
    /// 获取登录用户的路由
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    [OperLog("获取用户菜单", OperEnum.Select)]
    public async Task<MessageModel<SysUserMenuOut>> GetUserMenu()
    {
        var user = await _sysUserService.GetUserMenu(_user.ID);
        return Success(user);
    }
}
